/**
 * 
 */
package com.sms.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.sms.businessservice.CreateUserBusinessService;
import com.sms.vo.CreateUserVO;

/**
 * @author Sahdev Kamboj
 *
 */
public class CreateUserController extends MultiActionController {
	
	private static final Logger LOG = Logger.getLogger(CreateUserController.class);
	private BindingResult errors = null;
	private CreateUserBusinessService createUserBusinessService;
	/**
	 * @return the createUserBusinessService
	 */
	public CreateUserBusinessService getCreateUserBusinessService() {
		return createUserBusinessService;
	}
	/**
	 * @param createUserBusinessService the createUserBusinessService to set
	 */
	public void setCreateUserBusinessService(CreateUserBusinessService createUserBusinessService) {
		this.createUserBusinessService = createUserBusinessService;
	}
	
	
	@Override
	protected void bind(HttpServletRequest request, Object command) throws Exception {
		LOG.debug("bind(HttpServletRequest request, Object command) throws Exception : " + request + "[ Object : " + command);
		final ServletRequestDataBinder binder = new ServletRequestDataBinder(command);
		binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
		binder.bind(request);
		errors = binder.getBindingResult();

	}

	public ModelAndView showCreateUserUI(HttpServletRequest request, HttpServletResponse response) throws Exception {
		final Map<String, Object> model = new HashMap<String, Object>();
		CreateUserVO createUserVO = new CreateUserVO();
		model.put("createUserVO", createUserVO);
		return new ModelAndView("CreateUser", model);
	}

	public ModelAndView saveCreateUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
		final Map<String, Object> model = new HashMap<String, Object>();
		CreateUserVO createUserVO = new CreateUserVO();
		bind(request, createUserVO);
			if (errors == null || errors.getAllErrors() == null || errors.getAllErrors().size() == 0) {
				createUserBusinessService.saveCreateUser(createUserVO);
				model.put("infoMsg", "User.list.updated");
			} else {
				model.put("error", errors);

			}
			model.put("createUserVO", createUserVO);
		return new ModelAndView("CreateUser", model);

	}



}
